package com.quotemanager.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.quotemanager.businessbean.ProductTypeBean;
import com.quotemanager.dataobject.ProductType;
import com.quotemanager.form.ProductTypeMaintenanceForm;

public class ProductTypeMaintenanceAction extends DispatchAction {
	
	private ProductTypeBean productTypeBean = new ProductTypeBean();

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			ProductType[] productTypes = productTypeBean.getAllProductTypes();
			request.setAttribute("productTypes", productTypes);
			//ProductTypeMaintenanceForm maintenanceForm = (ProductTypeMaintenanceForm) form;
			//maintenanceForm.setProductTypes(productTypes);
			return super.execute(mapping, form, request, response);
		} catch (Exception e) {
			return mapping.findForward("success");
		}
	}
	
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ProductTypeMaintenanceForm productTypeMaintenanceForm = (ProductTypeMaintenanceForm)form;
		ProductType productType = productTypeMaintenanceForm.getProductType();
		productTypeBean.registerProduct(productType);
		return mapping.findForward("success");
	}
	
	public ActionForward edit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ProductTypeMaintenanceForm productTypeMaintenanceForm = (ProductTypeMaintenanceForm)form;
		int productTypeId = 0;
		try {
			productTypeId = Integer.parseInt(productTypeMaintenanceForm.getProductTypeId());
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
		ProductType productType = productTypeBean.getProductTypeById(productTypeId);
		productTypeMaintenanceForm.setProductTypeName(productType.getProductTypeName());
		productTypeMaintenanceForm.setProductTypeDescription(productType.getProductTypeDescription());
		System.out.println(productTypeMaintenanceForm.getHandlerMethod());
		return mapping.findForward("success");
		
	}
	
	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ProductTypeMaintenanceForm productTypeMaintenanceForm = (ProductTypeMaintenanceForm)form;
		ProductType productType = productTypeMaintenanceForm.getProductType();
		productTypeBean.updateProductType(productType);
		return mapping.findForward("success");
	}
	
}
